const Controller = require("egg").Controller;

class UserController extends Controller {
  // 注册
  async reg() {
    const { ctx } = this;
    const { phone, password } = ctx.request.body;
    const userService = ctx.service.user;
    ctx.validate(
      {
        phone: { type: "string", required: true, desc: "手机号" },
        password: { type: "string", required: true, desc: "密码" },
        repassword: { type: "string", required: true, desc: "确认密码" }
      },
      {
        // 判断密码和确认密码是否一致
        equals: [["password", "repassword"]]
      }
    );
    if (await userService.findByPhone(phone)) {
      ctx.throw(409, "用户已存在");
    }
    const user = await userService.createUser(phone, password);
    if (!user) {
      ctx.throw(500, "注册失败");
    }
    ctx.apiSuc("注册成功", user);
  }
  // 登录
  async login() {
    const { ctx } = this;
    const { phone, password } = ctx.request.body;
    const userService = ctx.service.user;
    // 验证该用户是否存在|验证该用户状态是否启用
    let user = await userService.findByPhone(phone);
    if (!user || user.status === "0") {
      ctx.throw(400, "用户不存在或已被禁用");
    }
    // 验证密码
    await userService.validatePassword(password, user.password);
    // 转json
    user = JSON.parse(JSON.stringify(user));
    // 生成token
    const token = await userService.generateToken({
      id: user.id,
      username: user.username,
      phone: user.phone
    });
    // const userInfo = await userService.verifyToken(token);
    // console.log(userInfo);
    // 赋值给user对象
    user.token = token;
    // 取消密码展示
    delete user.password;
    ctx.apiSuc("登录成功", user);
  }
  // 获取当前用户
  async info() {
    const { ctx } = this;
    const user = ctx.tokenUser;
    ctx.apiSuc("获取成功", user);
  }
  // 列表
  async list() {
    const { ctx } = this;
    const userService = ctx.service.user;
    let username = ctx.query.username;
    let phone = ctx.query.phone;
    const user = await userService.findByUsernameAndPhone(username, phone);
    ctx.apiSuc("获取成功", user);
  }
  // 编辑当前用户
  async edit() {
    const { ctx, service } = this;
    // const id = +ctx.params.id;
    const body = ctx.request.body;
    const userService = service.user;
    const user = await userService.editCurrentUser(body);
    ctx.apiSuc("更新成功", user);
  }

  // 注销当前用户
  async logout() {
    const { ctx, service } = this;
    const userService = service.user;
    const user = await userService.logoutCurrentUser();
    ctx.apiSuc("注销成功", user);
  }
}

module.exports = UserController;
